import Taro from "@tarojs/taro";
import { useRef, useState } from "react";
import { Canvas, Image, View } from "@tarojs/components";
import { useMount, useReactive, useUpdateEffect } from "ahooks";
import drawQrcode from "weapp-qrcode-canvas-2d";
import { nextTick } from "process";

type ByQrcodeProps = {
  /**
   * 二维码文本
   */
  text?: string;

  /**
   * 二维码周边空白大小
   */
  padding?: number;

  /**
   * 图片大小
   */
  width?: number; // 图片大小

  /**
   *  码的颜色
   */
  darkColor?: string;

  /**
   * 整体背景色
   */
  lightColor?: string;
};

export default ({
  text,
  padding,
  width = 300,
  lightColor,
  darkColor,
}: ByQrcodeProps) => {
  const [path, setPath] = useState<string>();

  const canvasRef = useReactive({ value: undefined });

  const toCreate = () => {
    const canvas = canvasRef.value;

    // var img = ctx.createImage();
    // img.src = "/static/images/logo.png";

    // img.onload = function () {
    drawQrcode({
      text,
      canvas,
      // type: "image/png",
      width,
      // scale: 10,
      // qzone: 0,
      padding,
      color: {
        // 背景
        light: lightColor,
        // 码的颜色
        dark: darkColor,
      },
      // image: {
      //   imageResource: img,
      //   width: 80, // 建议不要设置过大，以免影响扫码
      //   height: 80, // 建议不要设置过大，以免影响扫码
      //   round: true, // Logo图片是否为圆形
      // },
    });

    // 获取临时路径（得到之后，想干嘛就干嘛了）

    const size = width;

    Taro.canvasToTempFilePath({
      // canvasId: 'myQrcode',
      canvas,
      x: 0,
      y: 0,
      width: size,
      height: size,
      destWidth: size,
      destHeight: size,
      success(res) {
        setPath(res.tempFilePath);
      },
      fail(res) {
        console.error(res);
      },
    });
  };

  useMount(() => {
    Taro.createSelectorQuery()
      .select("#myCanvas")
      .fields({ node: true, size: true })
      .exec((res) => {
        canvasRef.value = res[0].node;
      });
  });

  useUpdateEffect(() => {
    if (!text) {
      setPath("");
    } else if (canvasRef.value) {
      toCreate();
    }
  }, [text, canvasRef.value]);

  return (
    <View
      className="inline-block relative"
      style={{ width: width + "rpx", height: width + "rpx" }}
    >
      <Canvas
        type="2d"
        id="myCanvas"
        className="absolute w-full h-full -top-[1000px] -left-[1000px]"
      />
      {path && <Image src={path} className="w-full h-full" />}
    </View>
  );
};
